package com.youmans.userservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youmans.common_utils.config.Result;
import com.youmans.common_utils.vo.UserForPic;
import com.youmans.common_utils.vo.UserQuery;
import com.youmans.userservice.entity.YoumansUser;
import com.youmans.userservice.service.YoumansUserService;
import com.youmans.userservice.utils.SaltUtils;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.bytebuddy.asm.Advice;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author youmans
 * @since 2022-10-17
 */
//@CrossOrigin
@RestController
@RequestMapping("/admin/user")
public class YoumansUserController {

    @Autowired
    private YoumansUserService youmansUserService ;

    @ApiOperation("查询所有用户，id和用户名")
    @GetMapping("findAll")
    public List<UserForPic> findAllTeacher() {
        //调用service方法
        List<UserForPic> list = youmansUserService.list();
        return list ;
    }


    // remove/1
    //2 逻辑删除讲师
    @ApiOperation("逻辑删除用户")
    @DeleteMapping("remove/{id}")
    public Result removeTeacher(@ApiParam(name = "id", value = "ID", required = true)
                                @PathVariable Integer id) {
        boolean isSuccess = youmansUserService.removeById(id);
        if(isSuccess) {
            return Result.ok(null);
        } else {
            return Result.fail(null);
        }
    }


    @ApiOperation(value = "新增")
    @PostMapping("save")
    public Result save(@RequestBody YoumansUser user) {
        if(!StringUtils.isEmpty(user.getUsername())){
            String byname = youmansUserService.getIdByname(user.getUsername());
            if(StringUtils.isEmpty(byname)){

                user.setIsDeleted(0);
                user.setAvatar("https://gulimall-station.oss-cn-hangzhou.aliyuncs.com/2022-04-27/3892a1e224194ab0ae5df478f651ba43.png") ;
                //1.生成随机盐
                String salt = SaltUtils.getSalt(8);
                Md5Hash md5Hash = new Md5Hash("123456",salt,1024);
                user.setPassword(md5Hash.toHex());
                //2.将随机盐保存到数据
                user.setSalt(salt);
                boolean save = youmansUserService.save(user);
                if (save){
                    return Result.ok().message("添加成功");
                }else{
                    return Result.fail().message("添加失败");
                }
            }
        }
        return Result.fail().message("用户名已存在，请重新输入用户名！");
    }

    @ApiOperation(value = "获取")
    @GetMapping("get/{id}")
    public Result get(@PathVariable Long id) {
        YoumansUser user = youmansUserService.getById(id);
        return Result.ok(user);
    }

    @ApiOperation(value = "获取所有用户名")
    @GetMapping("getUserNames")
    public Result getUserNames() {
        List<String> userNames = youmansUserService.getUserNames();
        return Result.ok(userNames);
    }

    @ApiOperation(value = "获取username模糊id集合")
    @GetMapping("getUserIdByname")
    public String getUserIdByname(@Param("username") String username) {
        String str = youmansUserService.getUserIdByname(username);
        return str ;
    }

    @ApiOperation(value = "获取userInfo")
    @GetMapping("getUserInfoByName")
    public YoumansUser getUserInfoByName(@Param("username") String username) {
        YoumansUser userInfo = youmansUserService.getUserInfoByName(username);
        return userInfo ;
    }

    @ApiOperation(value = "获取id")
    @GetMapping("getIdByname")
    public String getIdByname(String username) {
        String set = youmansUserService.getIdByname(username);
        return set ;
    }

    @ApiOperation(value = "修改")
    @PutMapping("update")
    public Result updateById(@RequestBody YoumansUser user) {
        String id = youmansUserService.getIdByname(user.getUsername());
        YoumansUser byId = youmansUserService.getById(user.getUserId());
        if(StringUtils.isEmpty(id)){
            boolean b = youmansUserService.updateById(user);

            return b?Result.ok().message("修改成功"):Result.fail().message("更新失败，请重试");
        }else if(id.equals(byId.getUserId().toString())){
            boolean b = youmansUserService.updateById(user);
            return b?Result.ok().message("修改成功"):Result.fail().message("更新失败，请重试");
        }
        return Result.fail().message("用户名已存在，请重新输入！");
    }

    @ApiOperation(value = "根据id列表删除")
    @DeleteMapping("batch-remove")
    public Result batchRemove(@RequestBody List<Long> idList) {
        youmansUserService.removeByIds(idList);
        return Result.ok(null);
    }

    //条件查询分页列表
    @ApiOperation(value = "获取分页列表")
    @PostMapping("{page}/{limit}")
    public Result index(
            @ApiParam(name = "page", value = "当前页码", required = true)
            @PathVariable Long page,
            @ApiParam(name = "limit", value = "每页记录数", required = true)
            @PathVariable Long limit,
            @ApiParam(name = "teacherVo", value = "查询对象", required = false)
    @RequestBody(required = false) UserQuery userQuery) {
        //创建page对象，传递当前页和每页记录数
        Page<YoumansUser> pageParam = new Page<>(page, limit);
        //封装条件
        QueryWrapper<YoumansUser> wrapper = new QueryWrapper<>();
        //获取条件值
        if(!StringUtils.isEmpty(userQuery)){
            String name = userQuery.getUsername();//名称
            Integer status = userQuery.getStatus();//状态
            String email = userQuery.getEmail();//邮箱
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("username",name);
        }
        if(!StringUtils.isEmpty(email)) {
            wrapper.like("email",email);
        }
        if(!StringUtils.isEmpty(status)) {
            wrapper.eq("status",status);
        }

        }
        //调用方法得到分页查询结果
        IPage<YoumansUser> pageModel = youmansUserService.page(pageParam, wrapper);
        return Result.ok(pageModel);
    }

}

